package com.seata.logic.visualize.tcc.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.seata.logic.visualize.dao.TblOrderMapper;
import com.seata.logic.visualize.dto.OrderCreateDto;
import com.seata.logic.visualize.entity.TblOrder;
import com.seata.logic.visualize.service.impl.TblOrderServiceImpl;
import com.seata.logic.visualize.tcc.OrderTccAction;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 蚂蚁会花呗
 * @date 2021/9/26 16:15
 */
@Service
public class OrderTccActionImpl implements OrderTccAction {

    static Log log = LogFactory.getLog(TblOrderServiceImpl.class);

    @Autowired
    private TblOrderMapper tblOrderMapper;


    @Override
    @Transactional
    public boolean createOrder(BusinessActionContext businessActionContext, OrderCreateDto orderCreateDto) {
        //创建订单
        log.info("创建订单开始！");
        orderCreateDto.setStatus(1);
        int result = tblOrderMapper.insert(orderCreateDto);
        log.info("创建订单：tcc一阶段try成功");
        return result > 0;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext businessActionContext) {
        String order = JSON.toJSONString(businessActionContext.getActionContext("order"));
        OrderCreateDto createDto = JSON.parseObject(order,OrderCreateDto.class);
        createDto.setStatus(0);
        int result = tblOrderMapper.update(createDto,new LambdaQueryWrapper<TblOrder>().eq(TblOrder::getId,createDto.getId()));
        log.info("创建订单：tcc二阶段commit成功");
        return result > 0;
    }

    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {
        String order = JSON.toJSONString(businessActionContext.getActionContext("order"));
        OrderCreateDto createDto = JSON.parseObject(order,OrderCreateDto.class);
        int result = tblOrderMapper.delete(new LambdaQueryWrapper<TblOrder>().eq(TblOrder::getId,createDto.getId()));
        log.info("创建订单：tcc二阶段回滚成功");
        return result > 0;
    }
}
